package com.le.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.le.edu.domain.entity.User;
import com.le.edu.domain.screen.SexVO;
import com.le.edu.domain.vo.UserVO;
import com.le.edu.exception.AppException;
import com.le.edu.mapper.UserMapper;
import com.le.edu.resp.ResultCodeEnum;
import com.le.edu.service.UserService;
import com.le.edu.utils.ClientUtils;
import com.le.edu.utils.ConstUtils;
import com.le.edu.utils.JwtUtils;
import com.le.edu.utils.PasswordEncoder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 17447
 * @description 针对表【t_user(会员表)】的数据库操作Service实现
 * @createDate 2023-12-27 19:22:43
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    private final RedisTemplate redisTemplate;

    public String login(String username, String password, ClientUtils.ClientEnum clientEnum) {
        User user = lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        if (null == user) {
            throw new AppException(ResultCodeEnum.USER_NOT_EXIST);
        }

        if (!PasswordEncoder.decrypt(password, user.getPassword())) {
            throw new AppException(ResultCodeEnum.USER_ACCOUNT_PWD_ERROR);
        }

        //判断用户类型
        if (clientEnum == ClientUtils.ClientEnum.ADMIN_CLIENT) {
            //管理员权限
            if (!"0".equals(user.getStatus()) || !"1".equals(user.getUserType())) {
                throw new AppException(ResultCodeEnum.USER_ACCOUNT_DISABLED);
            }
        } else {
            //普通用户权限
            if (!"0".equals(user.getStatus()) || !"0".equals(user.getUserType())) {
                throw new AppException(ResultCodeEnum.USER_ACCOUNT_DISABLED);
            }
        }

        var token = JwtUtils.createToken(user.getUserId(), user.getUsername());
        //绑定当前token和用户关系； 完成7天免登录
        // 登录成功以后：1）、前端收到的令牌前端自己存1天，  2）、服务端配合前端这个令牌存1天
        redisTemplate.opsForValue().set(ConstUtils.USER_LOGIN_KEY + token,
                user, 1, TimeUnit.DAYS);
        return token;
    }

    @Override
    public int resetPassword(User user) {
        user.setPassword(PasswordEncoder.encrypt(user.getPassword()));
        return baseMapper.updateById(user);
    }

    @Override
    public void checkUsernameUnique(String username) {
        Long count = baseMapper.selectCount(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, username));
        if (count > 0) {
            throw new AppException("用户名已存在");
        }
    }

    @Override
    public void checkUsernameUniqueNeUserId(Long userId, String username) {
        Long count = baseMapper.selectCount(Wrappers.<User>lambdaQuery()
                .ne(User::getUserId, userId)
                .eq(User::getUsername, username));
        if (count > 0) {
            throw new AppException("用户名已存在");
        }
    }

    @Override
    public Page<UserVO> pageUserList(Page<UserVO> page, LambdaQueryWrapper<User> wrapper) {
        return baseMapper.selectPageUserList(page, wrapper);
    }

    @Override
    public SexVO computeSexRatio() {
        return baseMapper.computeSexRatio();
    }
}




